<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div />
        <el-form-item>
          <el-button type="primary" @click="onVisible(1)">新增</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column prop="headpicurl" label="头像" width="80" align="center">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.headpicurl" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="登录名" align="center" />
      <el-table-column prop="roid" label="当前角色" align="center">
        <template slot-scope="scope">
          <span>{{ RoleList2[scope.row.roid] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="valid" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.valid" :disabled="scope.row.id == 1" :active-value="1" :inactive-value="0"
            @change="(val) => { return SetValid(val, scope.row) }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.id != 1" size="mini" type="primary" @click="onVisible(2, scope.row)">编辑</el-button>
          <!-- <el-button v-if="scope.row.id != 1" size="mini" type="danger" @click="onDelete(scope.row)">删除</el-button> -->
          <el-button size="mini" type="danger" @click="onPwd(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="totalCount > 10" layout="prev, pager, next" :total="totalCount"
      @current-change="idx => { PageIndex = idx }" />

    <el-dialog :close-on-click-modal="false" :title="visibleType == '1' ? '新增' : '修改'" :visible.sync="dialogVisible"
      @closed="handleClose">
      <el-form ref="forms" :rules="rulesModel" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="username">
          <el-input v-model="form.username" :rows="2" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色分配" prop="roid">
          <el-select v-model="form.roid" placeholder="请选择">
            <el-option v-for="item in RoleList" :key="item.id" :label="item.rolename" :value="Number(item.id)" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="visibleType == '1'" label="初始密码" prop="password">
          <el-input v-model="form.password" :rows="2" placeholder="请输入初始密码" type="password" />
        </el-form-item> -->
        <el-form-item label="状态" prop="valid">
          <el-switch v-model="form.valid" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEdit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="重置密码" :visible.sync="pwdVisble" @closed="handleClose(2)">
      <el-form ref="forms1" :rules="rules2" :model="from1" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="from1.password" :rows="2" placeholder="请输入重置密码" type="password" />
        </el-form-item>
        <el-form-item label="再次确认" prop="twoPassword">
          <el-input v-model="from1.twoPassword" :rows="2" placeholder="再次确认" type="password" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pwdVisble = false">取 消</el-button>
        <el-button type="primary" @click="onCheakPwd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  GetPage_SysUsers,
  SetValid_SysUsers,
  AddEdit_SysUsers,
  Delete_Users,
  SetPwd,
  GetPage_Role
} from '@/api/sys.js'

export default {
  name: 'Name',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.from1.password) {
        console.log(value)
        console.log(this.from1.password)
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      from1: {
        password: '',
        twoPassword: ''
      },
      form: {},
      RoleList: [],
      RoleList2: {},

      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      dialogVisible: false,
      visibleType: '',

      pwdVisble: false,
      pwdMsg: {},

      rulesModel: {
        username: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roid: [
          { required: true, message: '请输入分配角色', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入初始密码', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入模块权限名称', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      rules2: {
        password: [
          { required: true, message: '请输入初始密码', trigger: 'blur' }
        ],
        twoPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    PageIndex(val) {
      this.getData()
    }
  },
  mounted() {
    this.getRoleList()
    this.getData()
  },
  methods: {
    setFrom() {
      this.form = {
        id: 0,
        roid: '',
        username: '',
        password: '', // 初始密码
        valid: 1
      }
    },
    async onCheakPwd() {
      this.$refs['forms1'].validate(async (valid) => {
        if (valid) {
          const { success, msg } = await SetPwd({
            userid: this.pwdMsg.id,
            pwd: this.from1.password
          })
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
          this.pwdVisble = false
        } else {
          return false
        }
      })
    },
    onPwd(val) {
      this.pwdMsg = val
      this.pwdVisble = true
    },
    // 状态
    async SetValid(val, item) {
      const { success, msg } = await SetValid_SysUsers({
        userid: item.id,
        valid: val
      })
      if (success) {
        this.getData()
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    async onDelete(item) {
      try {
        const confirm = await this.$confirm('此操作将删除该配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm == 'confirm') {
          const { success, msg } = await Delete_Users([item.id])
          this.getData()
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        }
      } catch (e) {
        // 取消
        console.log(e)
      }
    },
    /**提交（新增编辑） */
    async onEdit() {
      try {
        await this.$refs['forms'].validate()
      } catch (e) {
        console.log(e)
        return
      }
      
      console.log(this.form)
      const { success, msg } = await AddEdit_SysUsers(this.form, this.visibleType)
      if (success) {
        this.dialogVisible = false
        this.getData()
      }
      this.$message({
        message: msg,
        type: success ? 'success' : 'error'
      })
    },
    async getRoleList() {
      const { list } = await GetPage_Role({
        PageIndex: 1,
        PageSize: 10000
      })
      list.forEach(item => {
        this.RoleList2[item.id] = item.rolename
      })
      this.RoleList = list.filter(item => {
        return item.id != 1
      })
    },
    // 关闭前
    handleClose(type = 1) {
      if (type == 1) {
        this.$refs.forms.resetFields()
        this.$refs.forms.clearValidate()
      } else {
        this.$refs.forms1.resetFields()
        this.$refs.forms1.clearValidate()
      }
    },
    // 打开前
    onVisible(type, item = {}) {
      this.visibleType = type
      this.setFrom()
      this.form = { ...this.form, ...item }
      console.log(this.form)
      this.dialogVisible = true
    },
    async getData(address) {
      this.listLoading = true
      const { list, pageIndex, totalCount } = await GetPage_SysUsers({
        PageIndex: this.PageIndex,
        PageSize: 10
      })
      this.totalCount = totalCount
      this.tableData = list
      this.listLoading = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}
</style>
